<template>
  <v-layout type="main">
    <div v-if="version != null">

      <div class="layout-top">
        <div class="rollback" @click="$router.push('/task')">
          <img src="~@/assets/img/prev.png" alt="">
          <span>返回</span>
        </div>

        <div class="code-description">
          <div class="dea_top">
            <div>
              <el-image class="nav_box" :src="detailData.avatar ? detailData.avatar : require('@/assets/img/drone3.jpg')" fit="fit"></el-image>
            </div>

            <div class="header_box">
              <div class="code-desc-header">
                <div class="title">
                  <div class="title-header">
                    <span>{{ detailData.name }}</span>
                  </div>

                  <div class="code-tags">
                    <div class="user-tag tag">
                      <img src="~@/assets/img/user.png" alt="">
                      {{
                        detailData.create_user && (detailData.create_user.nick_name ||
                          detailData.create_user.username)
                      }}
                    </div>

                    <div :class="['status-tag tag', {
                          'danger': version.status === 'terminated',
                          'warning': version.status != 'terminated' && version.status != 'running',
                          'success': version.status === 'running'
                        }]">
                      {{ statusMap[version.status] }}
                    </div>

                    <div class="version-tag tag">
                      <div class="ver-title">
                        <!--                        <img src="~@/assets/img/branch.png" alt="">-->
                        <img src="~@/assets/img/selectIcon.png" alt="">
                        <span>版本 {{ version.version }}</span>
                        <i class="el-icon-arrow-down el-icon--right"></i>
                      </div>
                      <div class="content">
                        <div class="ver-item" v-for="item in versionOptions" :key="item.id"
                             @click="dropdownChange(item)">
                          {{ item.version }}
                        </div>
                      </div>
                    </div>

                    <div class="time-tag tag">
                      <span>创建时间：</span>
                      {{ detailData.create_time }}
                    </div>

                  </div>

                  <div class="staet_box">
                    <plug-state :statusStr="version.status"/>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>


        <div class="btns-container">
          <div class="alick-handle-btns">
            <el-button class="handle-btn" type="success" size="medium" @click="start"
                       v-show="version.status == 'terminated'">
              启动
            </el-button>
            <el-button class="handle-btn" type="danger" size="medium" @click="stop"
                       v-show="version.status != 'terminated'">
              停止
            </el-button>

            <el-popover placement="bottom-end" width="70" trigger="hover" popper-class="popoverStyle">
              <div class="alick-popover-handle-btns">
                <el-button class="handle-btn" type="warning" size="medium" @click="exportModel">导出模型</el-button>
                <el-button class="handle-btn" type="warning" size="medium" @click="addVersion">新增版本</el-button>
              </div>
              <el-button class="handle-btn more_btn" type="warning" size="medium" slot="reference">更多</el-button>
            </el-popover>
          </div>
        </div>
      </div>

      <div class="radio_box">
        <el-radio-group v-model="nowRouter" v-show="!$route.meta.hideDetails" @input="skip">
          <el-radio-button :label="e.name" :name="`${e.name}`" v-for="(e, i) in thisRouter" :key="i">
            {{ e.meta.title }}
          </el-radio-button>
        </el-radio-group>
      </div>

      <div :class="['layout-content', { 'layout-content-nodetail': $route.meta.hideDetails }]">
        <router-view class="content-detail" :detailData="detailData" :version.sync="version" v-if="version != null"/>
      </div>

      <!-- <el-form class="form myself-form" ref="taskForm" :model="taskForm" :rules="taskSubmitRules" label-width="120px">
        <el-dialog :visible.sync="showTaskDialog" title="模型训练" width="840px">
          <el-form-item label="名称" prop="name">
            <el-input type="text" v-model="taskForm.name" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input type="textarea" :rows="3" v-model="taskForm.desc" />
          </el-form-item>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="commitTask">确定</el-button>
            <el-button class="none-type" @click="cancelTask">取消</el-button>
          </span>
        </el-dialog>
      </el-form> -->

      <div v-if="showExportModelDialog">
        <plug-export-model :show_file=showExportModelDialog @infoShow="infoShowExport" :model_id=model_id
                           :biz_id=version.id :business_type="2"/>
      </div>
    </div>
  </v-layout>
</template>

<script>

import {getModelBySource} from "@/api/model"
import plugExportModel from '@/components/module/plug-export-model'
import {
  getTaskDetail,
  getTaskVersionDetail,
  getAllTaskVersions,
  startTaskVersion,
  stopTaskVersion,
  createPvc,
  deletePvc
} from '@/api/task'
import plugState from '@/components/module/plug-state'

export default {
  data() {
    return {
      nowRouter: this.$route.name,
      thisRouter: [],
      detailData: {},
      version: null,
      versionOptions: [],
      modelForm: {},
      taskForm: {visibility: 0},
      taskSubmitRules: {
        name: [
          {required: true, message: "该项为必填项"},
          {required: true, min: 1, max: 40, message: "长度在1到40个字符"},
        ],
        desc: [
          {required: true, message: "该项为必填项"},
          {required: true, min: 1, max: 200, message: "长度在1到200个字符"},
        ],
      },
      showTaskDialog: false,
      showExportModelDialog: false,
      modelOptions: [],
      model: null,
      source_version_id: this.$route.query.source_version_id,
    };
  },
  components: {
    plugExportModel,
    plugState,
  },
  methods: {
    dropdownChange(val) {
      this.version = val;
      this.versionChange()
    },
    skip() {
      let path = `/task/${this.thisRouter.filter(e => e.name == this.nowRouter)[0].path}`
      if (path == this.$route.path) return
      this.$router.push({
        path,
        query: {
          id: this.$route.query.id
        }
      })
    },
    async getTaskVersions() {
      let ret = await getAllTaskVersions({taskId: this.$route.query.id})
      this.versionOptions = ret.data
      let ve = null
      if (this.versionOptions.length > 0) {
        if (this.$route.query.version) {
          ve = this.versionOptions.filter(item => item.version === this.$route.query.version)[0]
        } else {
          ve = this.versionOptions[0]
        }
      }
      if (this.source_version_id) {
        for (let i = 0; i < this.versionOptions.length; i++) {
          if (this.source_version_id == this.versionOptions[i].id) {
            ve = this.versionOptions[i]
          }
        }
      }
      let res = await getTaskVersionDetail({id: ve.id})
      let data = res.data
      this.version = data
      console.log("version",this.version)
      this.$forceUpdate();
    },
    async versionChange() {
      let res = await getTaskVersionDetail({id: this.version.id})
      let data = res.data
      this.version = data
      this.detailData = JSON.parse(JSON.stringify(this.detailData))
    },
    async getDetail() {
      if (this.$route.query.id) {
        let res = await getTaskDetail({id: this.$route.query.id})
        this.detailData = res.data
        this.taskForm = JSON.parse(JSON.stringify(this.detailData))
        this.getTaskVersions()

      }
    },
    // updateTask() {
    //   this.showTaskDialog = true
    // },
    // commitTask() {
    //   this.$refs.taskForm.validate(async (valid) => {
    //     if (valid) {
    //       await putTask(this.task)
    //       this.showTaskDialog = false
    //     }
    //   })
    // },
    // cancelTask() {
    //   this.showTaskDialog = false
    // },
    updateVersion() {
      if (this.version) {
        let query = {
          id: this.version.id
        }
        this.$router.push({
          path: '/task/versionsdetail',
          query
        })
      }
    },
    addVersion() {
      let version = 1
      if (this.detailData.version_index) {
        version = 'v' + (this.detailData.version_index + 1)
      }
      let query = {
        task_id: this.detailData.id,
        version: version,
        source_version_id: this.version.id
      }
      this.$router.push({
        path: '/task/versionsdetail',
        query
      })
    },
    async exportModel() {
      if (!this.$route.query.id) return
      let data = {
        source: this.version.id
      }
      let res = await getModelBySource(data);
      if (res && res.data) {
        this.model_id = res.data.id
      }
      this.showExportModelDialog = true
      console.log("showExportModelDialog", this.showExportModelDialog)
    },
    infoShowExport(data) {
      this.showExportModelDialog = data
    },

    async start() {
      if (this.version) {
        try {
          var res = await createPvc({id: this.version.id})
          console.log("res:", res)
          var res1 = await startTaskVersion({id: this.version.id});
          if (res1.code != 200) {
            await deletePvc({id: this.version.id})
          }
        } catch (e) {
          //console.log("e:",e)
          await deletePvc({id: this.version.id})
        }
      }

    },
    async stop() {
      if (this.version) {
        await stopTaskVersion({id: this.version.id});
        this.getDetail()
        this.getTaskVersions()
      }
    },
    exportTask() {
    }
  },

  mounted() {
    let temp = this.$router.options.routes.filter(
      e => e.name == 'task' && e.children
    )
    this.thisRouter = temp[0].children.filter(e => !e.meta.hideDetails)

    this.getDetail()
    this.$EventBus.$on('task', e => {
      console.log(e)
      this.getDetail()
      this.getTaskVersions()
      // this.version = this.$router.query.version
    })
  },
  destroyed() {
    this.$EventBus.$off('task')
  },
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";
@import "~@/assets/css/task.less";

.el-dropdown-link {
  border: 1px solid rgba(#808080, .5);
  padding: 5px 10px;
  border-radius: 10px;
  position: relative;
  padding-left: 28px;
  background: #eee;
  top: 3px;

  span::before {
    content: "";
    width: 16px;
    height: 16px;
    background: url(~@/assets/img/branch.png) no-repeat center;
    background-size: cover;
    margin-top: 3px;
    position: absolute;
    left: 6px;
    top: 4px;
  }
}

.popoverStyle {
  .handle-btn {
    background: #8F5D23;
    border: none;
    margin-bottom: 0;
    padding: 15px 0;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #F7AF5B;

    &:hover {
      background: #E6A23C;
      color: #FFFFFF;
    }
  }
}

.more_btn{
  background: #8F5D23;
  border: none;
  &:hover{
    background: #E59941;
  }
}

</style>

<style lang="less">
.el-popover.popoverStyle {
  background: #8F5D23;
  padding: 15px 0;
}

//body .el-popper[x-placement^=bottom] .popper__arrow::after {
//  border: none;
//  background: #8F5D23;
//}
//
//.el-popper[x-placement^=bottom] .popper__arrow {
//  border-bottom-color: #8F5D23 !important;
//}
</style>
